package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.to.member.SocialUserTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberResVo;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;

import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@Slf4j
@RequestMapping("/oauth2.0")
public class OAuth2Controller {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private MemberFeignService memberFeignService;

    @RequestMapping("/weibo/success")
    public String weiBoSuccess(@RequestParam("code") String code) {

        String url = "https://api.weibo.com/oauth2/access_token";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
        queryParams.add("client_id", "c5ef297884bb56b9fbe4");
        queryParams.add("client_secret", "9568e995cc35326d58627089ae01269b8533aa62");
        queryParams.add("grant_type", "authorization_code");
        queryParams.add("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        queryParams.add("code", code);

        // 构建请求URL
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromUriString(url).queryParams(queryParams);

        // 创建请求实体
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);

        log.info("/weibo/success code is {}, url is {}", code, builder.toUriString());
        ResponseEntity<SocialUserTo> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, requestEntity, SocialUserTo.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            SocialUserTo to = response.getBody();
            log.info("access_token response is {}", to);
            // 获取到了社交用户信息,,调用 会员接口进行登录或者注册操作
            R r = memberFeignService.oauth2WeiboWeiboLogin(to);
            log.info("access_token R is {}", r);
            if (r.isOk()) {
                MemberResVo data = r.getData(new TypeReference<MemberResVo>() {
                });
                log.info("登录成功，用户信息为 {}", data);
                return "redirect:http://gulimall.com";
            }
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }


    @RequestMapping("/github/success")
    public String githubSuccess(@RequestParam("code") String code) {

        String url = "https://github.com/login/oauth/access_token";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
        queryParams.add("client_id", "c5ef297884bb56b9fbe4");
        queryParams.add("client_secret", "9568e995cc35326d58627089ae01269b8533aa62");
        queryParams.add("code", code);

        // 构建请求URL
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromUriString(url).queryParams(queryParams);

        // 创建请求实体
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);


        ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, requestEntity, String.class);
        String responseBody = response.getBody();

        log.info("请求进来, code = {}", code);
        log.info("response is {}", responseBody);

        return "redirect:http://gulimall.com";
    }


    @RequestMapping("/gitee/success")
    public String giteeSuccess(@RequestParam("code") String code, HttpSession httpSession) {

        // 创建授权request
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId("caf2485f327bff9076cbdddd94aba465dd662d74408f8f06a9d3d36620d04edc")
                .clientSecret("1583adcb3d6f51b9c5245498db233a33a72e672f2bef334c7aa068da27ea13dd")
                .redirectUri("http://auth.gulimall.com/oauth2.0/gitee/success")
                .ignoreCheckState(true)
                .build());
        // 生成授权页面
        // authRequest.authorize();

        // 授权登录后会返回code（auth_code（仅限支付宝））、state，1.8.0版本后，可以用AuthCallback类作为回调接口的参数
        // 注：JustAuth默认保存state的时效为3分钟，3分钟内未使用则会自动清除过期的state
        AuthCallback callback = new AuthCallback();
        callback.setCode(code);
        AuthResponse<AuthUser> response = authRequest.login(callback);

        R r = memberFeignService.oauth2Login(response.getData());
        if (r.isOk()) {
            MemberResVo data = r.getData(new TypeReference<MemberResVo>() {
            });
            log.info("登录成功，用户信息为 {}", data);
            // 将数据放入session
            httpSession.setAttribute(AuthConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
